// pages/cart/cart.js
const PAGES = require('../../utils/pages.js')
var base = require('../../base.js');  //路径可能做相应调整
const _ = base._; //翻译函数
const { HTTP } = require('../../lib/http.js')
const { URL } = require('../../lib/urls.js')
const { getUserToken, getUserInfo } = require('../../lib/user.js')
const app=getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    _t: [],
    dataList: [],
    totle: 0.00,
    isShowNullView: false,
    isChangeNum: true,
    isFullSucreen: app.globalData.isFullSucreen ? true : false //判断机型
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      _t: base._t(), //翻译
    });
    if (!getIsLogin()) {
      wx.navigateTo({
        url: PAGES.index,
      })
      return;
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      this.getTabBar().setData({
        selected: 2
      })
    }
    this.getNetCartList();
    this.getCartCount();
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getNetCartList();
  },

  //商品列表数量改变
  numchangeTap: function (e) {
    if(!this.data.isChangeNum){
      return;
    }
    var changType = e.currentTarget.dataset.types;
    var index = e.currentTarget.dataset.index;
    var model = this.data.dataList[index];
    var pice = 0;//商品价格
    if (changType == "add") {
      //数字增加
      if (model.Count >= model.Stock){
        wx.showToast({
          title: _("商品库存不足"),
          icon: 'none'
        })
        return;
      }
      model.Count += 1;
    } else if (changType == "minus") {
      //减
      if (model.Count <= 1) {
        return;
      }
      model.Count -= 1;
    }
    var list=[];
    for(var i in this.data.dataList){
      var xhmodel=this.data.dataList[i];
      list.push(i == index ? model : xhmodel);
      pice += (i == index ? model.SoldPrice * model.Count : xhmodel.SoldPrice * xhmodel.Count);
    }
    this.setData({
      dataList:list,
      totle: pice,
      isChangeNum:false,
    })
    this.changeCart(model);
  },
  //删除购物车
  delCartTap: function (e) {
    var index = e.currentTarget.dataset.index;
    var model = this.data.dataList[index];
    model.Count=0;
    this.delCart(model);
  },
  //获取购物车列表
  getNetCartList: function () {
    let that = this;
    HTTP({
      url: URL.goods.getCartList,
      userToken: getUserToken(),
      data: {
      },
      success: (ress) => {
        wx.stopPullDownRefresh();
        var res = ress.Data;
        console.log("hlw:" + res)
        if (res.CartInfos.length > 0) {
          var pice=0;
          for (var i in res.CartInfos) {
            var model = res.CartInfos[i];
            pice += model.SoldPrice * model.Count;
          }
          this.setData({
            dataList: res.CartInfos,
            isShowNullView: false,
            totle: pice,
          });
        } else {
          this.setData({
            dataList:[],
            isShowNullView: true,
            totle:0
          })
        }
      },
      fail: (res) => {
        console.log(res)
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
        if (this.data.dataList.length <1) {
          this.setData({
            isShowNullView: true,
          })
        }
      }
    })
  },
  //编辑购物车
  changeCart: function (model) {
    wx.showLoading({
      title: ''
    })
    var that = this;
    HTTP({
      url: URL.goods.changeCart,
      userToken: getUserToken(),
      data: {
        ProductCode: model.ProductCode,
        CartCode: model.CartCode,
        Count: model.Count,
        MemberId: getUserInfo().memberId,
        IsAdd:false,
      },
      success: (res) => {
        wx.hideLoading();
        that.cartNumChange();
        that.setData({
          isChangeNum:true
        });
      },
      fail: (res) => {
        console.log(res)
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
        that.setData({
          isChangeNum: true
        });
      }
    })
  },
  //删除购物车
  delCart: function (model) {
    var that = this;
    HTTP({
      url: URL.goods.cartDel,
      userToken: getUserToken(),
      data: {
        ProductCode: model.ProductCode,
        CartCode: model.CartCode,
        Count: model.Count,
        MemberId: getUserInfo().memberId,
      },
      success: (res) => {
        //删除购物车商品时
        var list = [];
        var pice = 0;
        for (var i in that.data.dataList) {
          var xhmodel = that.data.dataList[i];
          if (model.CartCode == xhmodel.CartCode) {
            continue;
          }
          pice += xhmodel.SoldPrice * xhmodel.Count;
          list.push(xhmodel);
        }
        that.setData({
          totle: pice,
          dataList: list,
          isShowNullView: list.length>0?false:true,
        })
        that.cartNumChange();
      },
      fail: (res) => {
        console.log(res)
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    })
  },
  /**
   * 提交订单
   */
  submitTap: function () {
    if(this.data.dataList.length<1){
      wx.showToast({
        title: _("购物车是空的"),
        icon: 'none'
      })
      return;
    }
    var list = [];
    for (var tindex in this.data.dataList) {
      var tmodel = this.data.dataList[tindex];
      var model=new Object();
      model.ProductCode = tmodel.ProductCode;
      model.amount = tmodel.Count;
      model.Name = tmodel.ProductName;
      model.MainImg = tmodel.ProductImg;
      model.SoldPrice = tmodel.SoldPrice;
      list.push(model);
    }
    let data = JSON.stringify(list);
    wx.navigateTo({
      url: PAGES.orderQrPt + '?data=' + encodeURIComponent(data),
    })
  },
  cartNumChange:function(){
    var num=0
    for (var i in this.data.dataList) {
      var xhmodel = this.data.dataList[i];
      num += xhmodel.Count;
    }
    var list = [];
    for (var i in this.getTabBar().data.list) {
      var model = this.getTabBar().data.list[i];
      if (i == 2) {
        model.tagNum = num;
      }
      list.push(model);
    }
    this.getTabBar().setData({
      list: list
    })
  },

  //获取购物车商品数量
  getCartCount: function () {
    let that = this;
    HTTP({
      url: URL.goods.cartCount,
      userToken: getUserToken(),
      data: {
      },
      success: (ress) => {
        var res = ress.Data;
        console.log("hlw:" + res)
        var list = [];
        for (var i in that.getTabBar().data.list) {
          var model = that.getTabBar().data.list[i];
          if (i == 2) {
            model.tagNum = res;
          }
          list.push(model);
        }
        that.getTabBar().setData({
          list: list
        })
      },
      fail: (res) => {
        console.log(res)
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    })
  },
})
